<?php

/***** Page Check functions (check which kind of page is) *****/

function is_home () {
    global $db_query;
    return $db_query->is_home;
}

function is_page () {
    global $db_query;
    return $db_query->is_page;
}

function is_login () {
    global $db_query;
    return $db_query->is_login;
}

function is_register () {
    global $db_query;
    return $db_query->is_register;
}

function is_services () {
    global $db_query;
    return $db_query->is_services;
}

function is_about () {
    global $db_query;
    return $db_query->is_about;
}

function is_contact () {
    global $db_query;
    return $db_query->is_contact;
}

function is_submit () {
    global $db_query;
    return $db_query->is_submit;
}

function is_queue () {
    global $db_query;
    return $db_query->is_queue;
}

function is_editpost () {
    global $db_query;
    return $db_query->is_editpost;
}

function is_user_home () {
    global $db_query;
    return $db_query->is_user_home;
}

function is_user_profile () {
    global $db_query;
    return $db_query->is_user_profile;
}

function is_user_submitted () {
    global $db_query;
    return $db_query->is_user_submitted;
}

function is_user_commented () {
    global $db_query;
    return $db_query->is_user_commented;
}

function is_search () {
    global $db_query;
    return $db_query->is_search;
}

function is_search_trip () {
    global $db_query;
    return $db_query->is_search_trip;
}

function is_search_plan () {
    global $db_query;
    return $db_query->is_search_plan;
}

function is_feed () {
    global $db_query;
    return $db_query->is_feed;
}

function is_tagcloud () {
    global $db_query;
    return $db_query->is_tagcloud;
}

function is_top10 () {
    global $db_query;
    return $db_query->is_top10;
}

function is_userlist () {
    global $db_query;
    return $db_query->is_userlist;
}

function is_post () {
    global $db_query;
    return $db_query->is_post;
}


function is_optionadmin () {
    global $db_query;
    return $db_query->is_optionadmin;
}

function is_tagadmin () {
    global $db_query;
    return $db_query->is_tagadmin;
}

function is_admin () {
    global $db_query;
    return $db_query->is_admin;
}

/***** Posts functions (They will all be called by template pages) *****/

function have_posts() {
    global $db_query;
    return $db_query->have_posts();
}

function the_post() {
    global $db_query;
    $db_query->the_post();
}

/***** Get Template functions *****/

function get_header() {
	if ( file_exists( TEMPLATEPATH . '/header.php') )
		require_once( TEMPLATEPATH . '/header.php');
	else
		require_once( ABSPATH . 'tr-themes/default/header.php');
}

function get_footer() {
	if ( file_exists( TEMPLATEPATH . '/footer.php') )
		require_once( TEMPLATEPATH . '/footer.php');
	else
		require_once( ABSPATH . 'tr-themes/default/footer.php');
}

function get_adsense() {
	if ( file_exists( TEMPLATEPATH . '/adsense.php') )
		require_once( TEMPLATEPATH . '/adsense.php');
	else
		require_once( ABSPATH . 'tr-themes/default/adsense.php');
}

/***** Date/Time tags *****/

function mysql2date($dateformatstring, $mysqlstring, $translate = true) {
	global $month, $weekday, $month_abbrev, $weekday_abbrev;
	$m = $mysqlstring;
	if (empty($m)) {
		return false;
	}
	$i = mktime(substr($m,11,2),substr($m,14,2),substr($m,17,2),substr($m,5,2),substr($m,8,2),substr($m,0,4)); 
	if (!empty($month) && !empty($weekday) && $translate) {
		$datemonth = $month[date('m', $i)];
		$datemonth_abbrev = $month_abbrev[$datemonth];
		$dateweekday = $weekday[date('w', $i)];
		$dateweekday_abbrev = $weekday_abbrev[$dateweekday]; 		
		$dateformatstring = ' '.$dateformatstring;
		$dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit($dateweekday_abbrev), $dateformatstring);
		$dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
		$dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
		$dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit($datemonth_abbrev), $dateformatstring);
	
		$dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
	}
	$j = @date($dateformatstring, $i);
	if (!$j) {
	// for debug purposes
	//	echo $i." ".$mysqlstring;
	}
	return $j;
}


/* Options functions */

function get_settings($setting) {
	global $trdb;

	$option = $trdb->get_var("SELECT option_value FROM $trdb->options WHERE option_name = '$setting'");

	if (!$option) :
		return false;
	endif;

	@ $kellogs = unserialize($option);
	if ($kellogs !== FALSE)
		return $kellogs;
	else return $option;

}

function get_option($option) {
	return get_settings($option);
}

function update_option($option_name, $newvalue) {
	global $trdb;
	
	if ( is_array($newvalue) || is_object($newvalue) )
		$newvalue = serialize($newvalue);

	$newvalue = trim($newvalue); // I can't think of any situation we wouldn't want to trim

    // If the new and old values are the same, no need to update.
    if ($newvalue == get_option($option_name)) {
        return true;
    }

	// If it's not there add it
	if ( !$trdb->get_var("SELECT option_name FROM $trdb->options WHERE option_name = '$option_name'") )
		add_option($option_name);

	$newvalue = $trdb->escape($newvalue);
	$trdb->query("UPDATE $trdb->options SET option_value = '$newvalue' WHERE option_name = '$option_name'");
	return true;
}

function add_option($name, $value = '', $description = '', $autoload = 'yes') {
	global $trdb;
	$original = $value;
	if ( is_array($value) || is_object($value) )
		$value = serialize($value);

	if( !$trdb->get_var("SELECT option_name FROM $trdb->options WHERE option_name = '$name'") ) {
		$name = $trdb->escape($name);
		$value = $trdb->escape($value);
		$description = $trdb->escape($description);
		$trdb->query("INSERT INTO $trdb->options (option_name, option_value, option_description, autoload) VALUES ('$name', '$value', '$description', '$autoload')");
		
	}
	return;
}

function delete_option($name) {
	global $trdb;
	// Get the ID, if no ID then return
	$option_id = $trdb->get_var("SELECT option_id FROM $trdb->options WHERE option_name = '$name'");
	if (!$option_id) return false;
	$trdb->query("DELETE FROM $trdb->options WHERE option_name = '$name'");
	return true;
}

/***** Security functions *****/

function apply_filters($string) {
	$myFilter = new InputFilter(array(), array(), 0, 0);
	$string = $myFilter->process($string);
	return $string;
}

// Look for serverconfiguration "get_magic_quotes_gpc"
function proofAddSlashes($in_string)
{
	if (get_magic_quotes_gpc()==1) {
		return $in_string;
	} else {
		return AddSlashes($in_string);
	}
}

function add_magic_quotes($array) {
	foreach ($array as $k => $v) {
		if (is_array($v)) {
			$array[$k] = add_magic_quotes($v);
		} else {
			$array[$k] = addslashes($v);
		}
	}
	return $array;
}

function filter_bodytext($bodytext){
    $bodytext= htmlspecialchars($bodytext, ENT_QUOTES);

    //$bodytext= str_replace ("\n"," ", $bodytext);
    $bodytext= str_replace ("\r","<br/>", $bodytext);
    
    return $bodytext;
}

function filter_bodytext_converse($bodytext){

    $bodytext= str_replace ("<br/>","\r", $bodytext);
    
    $bodytext= html_entity_decode($bodytext);
    
    return $bodytext;
}

function make_clickable($ret) {
	$ret = ' ' . $ret . ' ';
	$ret = preg_replace("#([\s>])(https?)://([^\s<>{}()]+[^\s.,<>{}()])#i", "$1<a href='$2://$3' rel='nofollow'>$2://$3</a>", $ret);
	$ret = preg_replace("#(\s)www\.([a-z0-9\-]+)\.([a-z0-9\-.\~]+)((?:/[^ <>{}()\n\r]*[^., <>{}()\n\r]?)?)#i", "$1<a href='http://www.$2.$3$4' rel='nofollow'>www.$2.$3$4</a>", $ret);
	$ret = preg_replace("#(\s)([a-z0-9\-_.]+)@([^,< \n\r]+)#i", "$1<a href=\"mailto:$2@$3\">$2@$3</a>", $ret);
	$ret = trim($ret);
	return $ret;
}

function updateTags($post_id,$post_tags){
	
	global $trdb;
	// get tags 

	$post_tags = str_replace("　", " ", $post_tags);
	$tags = explode(" ", $post_tags);
	$tag_count = count($tags);
	
	// do while to circle all the tags
	for($i=0;$i < $tag_count;$i++)
	{
		// check is tag exist
		$tag = $tags[$i];
		$query1 = "SELECT COUNT(*) FROM $trdb->tags WHERE tag_name = '$tag'";
		$exist_tag = $trdb->get_var($query1);
		
		// if tag not exist, insert tag into tr_tags
		if(($exist_tag == '0')&&($tag!=" ")) {
			$query_insert_tag = "INSERT INTO $trdb->tags (tag_name) VALUES ('$tag')";
			$trdb->query($query_insert_tag);
		}
		
		// select tag_ID
		$query2 = "SELECT tag_ID FROM $trdb->tags WHERE tag_name = '$tag'";
		$tagid = $trdb->get_var($query2);
		
		// insert record to relate post to tag
		$insert_post2tag = "INSERT INTO $trdb->post2tag (tag_id, post_id) VALUES ($tagid, $post_id)";
		$trdb->query($insert_post2tag);
		
	}
}

function checkTag($tag){
	
	global $trdb;
	
	// check is tag exist
	$query1 = "SELECT COUNT(*) FROM $trdb->tags WHERE tag_name = '$tag'";
	$exist_tag = $trdb->get_var($query1);
	
	// if tag not exist, insert tag into tr_tags
	if($exist_tag == '0') {
		$query_insert_tag = "INSERT INTO $trdb->tags (tag_name) VALUES ('$tag')";
		$trdb->query($query_insert_tag);
	}
		
	// select tag_ID
	$query2 = "SELECT tag_ID FROM $trdb->tags WHERE tag_name = '$tag'";
	$tagid = $trdb->get_var($query2);
		
	return $tagid;
}

function delTagRelated($post_id) {
	global $trdb;
	$request = "DELETE FROM $trdb->post2tag WHERE post_id = $post_id";
	$trdb->query($request);
	
}

function create_guid_old(){
   if (function_exists('com_create_guid')){
       return com_create_guid();
   }else{
       mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
       $charid = strtoupper(md5(uniqid(rand(), true)));
       $hyphen = chr(45);// "-"
       $uuid = chr(123);// "{"
       $uuid .= substr($charid, 0, 8).$hyphen
               .substr($charid, 8, 4).$hyphen
               .substr($charid,12, 4).$hyphen
               .substr($charid,16, 4).$hyphen
               .substr($charid,20,12)
               .chr(125);// "}"
       return $uuid;
   }
}

function create_guid(){
   if (function_exists('com_create_guid')){
       return com_create_guid();
   }else{
       mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
       $charid = strtoupper(md5(uniqid(rand(), true)));
       $hyphen = chr(45);// "-"
       // $uuid = chr(123)// "{"
       $uuid = substr($charid, 0, 8).$hyphen
               .substr($charid, 8, 4).$hyphen
               .substr($charid,12, 4).$hyphen
               .substr($charid,16, 4).$hyphen
               .substr($charid,20,12);
               //.chr(125);// "}"
       return $uuid;
   }
}

function is_guid($guid){
	if(strlen($guid)==36)
		return true;
	else
		return false;
}

function substr_for_gb2312($str,$start,$len=null)
{
  $totlelength = strlen($str);
  $shorten = false;

  if ($len == null) $len = $totlelength;
  if ($len ==0) return "";
  if ($len >= $totlelength && $start == 0 ) return $str;
  if ($start > $totlelength) return "";
  if ($len < $totlelength) $shorten = true;

  if ($start < 0 )
  {
      if ( abs($start) >= $totlelength ) $start = 0;
      else $start = $totlelength - abs($start);
  }
  
  if ($start > 0)
  {
      $i = $start-1;
      $flag = -1;
      while ($i >= 0)
      {
        if ( ord(substr($str,$i,1)) > 160)
        {
            $flag = -1*$flag;
        }
        else break;
        $i--;
      }
      if($flag==1)
      {
        $start = $start - 1;
        $len++;
      }
    }
    $str = substr($str,$start);
    $totlelength = strlen($str);

    if ($len<0) $len = $totlelength - abs($len);
    if ($len <= 0) return "";
    $i=min($len,$totlelength);
    $i--;
    $flag = -1;
    while ($i >= 0)
    {
      if (ord(substr($str,$i,1))>160)
      {
          $flag=-1*$flag;
      }
      else break;
      $i--;
    }
    if($flag == 1)
      $len=$len-1;
    $subit=substr($str,0,$len);
    
    if($shorten) $subit = $subit.'...';
    return $subit;
}

function check_url_format($url){
	if ($url == 'http://' || $url == "https://" || $url == "")
		return false;
	else return true;
}


function add_to_favor($user_id,$post_id){
	global $trdb;
	$request = "INSERT INTO $trdb->post2user (post_id, user_id) VALUES ($post_id, $user_id)";
	$trdb->query($request);
}

function add_to_favorplan($user_id,$plan_id){
	global $trdb;
	$request = "INSERT INTO $trdb->plan2user (plan_id, user_id) VALUES ($plan_id, $user_id)";
	$trdb->query($request);
}



function get_name_by_id($id, $echo = true) {
	global $trdb;
	$request = "SELECT user_login FROM $trdb->users WHERE ID=$id";
	$the_post_author = $trdb->get_var($request);
	if ($echo)
    	echo $the_post_author;
	else
		return $the_post_author;
}

function is_place_exist($tag) {
	global $trdb;
	$tag = $trdb->escape($tag);
	$request = "SELECT count(tag_ID) FROM $trdb->tags WHERE tag_name = '$tag'";
	$number = $trdb->get_var($request);
	if($number==0) return false;
	else return true;
}

function get_placeid_by_name($tagname) {
	global $trdb;
	$tagid=0;
	$tagname = $trdb->escape($tagname);
	$request = "SELECT count(tag_ID) FROM $trdb->tags WHERE tag_name = '$tagname'";
	$number = $trdb->get_var($request);
	if($number!=0){
		$request2 = "SELECT tag_ID FROM $trdb->tags WHERE tag_name = '$tagname'";
		$tagid = $trdb->get_var($request2);
	}
	return $tagid;
}

// PHP decodeURIComponent (javascript:encodeURIComponent)
function funky_javascript_fix($text) {
	
	//$text =  preg_replace("/\%u([0-9A-F]{4,4})/e",  "'&#'.base_convert('\\1',16,10).';'", $text);
	$text =  rawurldecode(iconv("UTF-8", "gb2312//IGNORE", $text));
	
	return $text;
}

function get_blog_charset()
{
    $charset = get_option('charset');
    if($charset==""){
        $charset = "gb2312";
    }
    echo $charset;
}

/**** Install ****/

function tr_die($message, $title = '') {
	global $wp_locale;

	header('Content-Type: text/html; charset=utf-8');

	if ( empty($title) )
		$title = __('Hologon &rsaquo; Error');

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title><?php echo $title ?></title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" href="install.css" type="text/css" />
</head>
<body>
	<h1 id="logo">Hologon Install</h1>
	<p><?php echo $message; ?></p>
</body>
</html>
<?php

	die();
}

function is_hologon_installed() {
	global $trdb;
	$trdb->hide_errors();
	$installed = $trdb->get_var("SELECT option_value FROM $trdb->options WHERE option_name = 'siteurl'");
	$trdb->show_errors();
	return $installed;
}
?>